import { message } from 'antd';
import {
  getRoleList,
  getResourceTree,
  getAuthByRoleCode,
  updateResourceActionListByRole,
  selectResourceActionByUser,
} from '../services';

const mapTreeData = (data) => {
  return data.map((item) => {
    return {
      title: item.resourceName,
      key: item.resourceId,
      code: item.resourceCode,
      actionInfoList: item.actionInfoList,
      children:
        item.childResourceList == null || item.childResourceList.length <= 0
          ? []
          : mapTreeData(item.childResourceList),
    };
  });
};
export default {
  namespace: 'authActManageModel',
  state: {
    roleList: [],
    roleListTotal: 0,
    resourceTree: [],
    resourceOfRole: {},
    resourceList: [],
  },
  effects: {
    *getRoleList({ payload }, { put, call, select }) {
      const res = yield call(getRoleList, payload);
      const { code, data, message: errMsg } = res;
      if (code === 0 && data) {
        const { dataList, total } = data;
        yield put({
          type: 'updateModel',
          payload: {
            roleList: dataList,
            roleListTotal: total,
          },
        });
      } else {
        message.error(errMsg);
      }
    },
    *getImportRoleList({ payload }, { put, call, select }) {
      return yield call(getRoleList, payload);
    },
    *getResourceTree({ payload }, { put, call, select }) {
      const res = yield call(getResourceTree, payload);
      const { code, data, message: errMsg } = res;
      if (code === 0 && data) {
        yield put({
          type: 'updateModel',
          payload: {
            resourceTree: mapTreeData(data?.childResourceList || []),
          },
        });
      } else {
        message.error(errMsg);
      }
    },
    *updateResourceActionListByRole({ payload }, { call }) {
      return yield call(updateResourceActionListByRole, payload);
    },
    *getAuthByRoleCodethen({ payload }, { call }) {
      return yield call(getAuthByRoleCode, payload);
    },
    *getAuthByRoleCode({ payload }, { put, call, select }) {
      const res = yield call(getAuthByRoleCode, payload);
      const { code, data, message: errMsg } = res;
      if (code === 0 && data) {
        yield put({
          type: 'updateModel',
          payload: {
            resourceOfRole: data?.actionMap || {},
            resourceList: data?.resourceList || [],
          },
        });
      } else {
        message.error(errMsg);
      }
    },
  },
  reducers: {
    /* 更新状态（通用） */
    updateModel: (state, { payload }) => ({
      ...state,
      ...payload,
    }),
  },
};
